﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Configuration;
using System.Web;
using System.Runtime.Caching;

namespace Ruandao.HostServer.Sql
{
    using Ruandao.HostServer.SqlEntityAccess;
    using Ruandao.Misc;

    public class SqlSiteWare : SiteWare
    {

        internal SiteWare SetFromEntity(SiteWareEntity entity)
        {
            TypeUtil.MapProperty(entity, this,
                "SiteWareId",
                "SiteGuid",
                "WareName",
                "CreateDate",
                "DatabaseId",
                "WareDbName",
                "FileStorageId",
                "WareFolder",
                "AccountContextCode",
                "RoleCategory",
                "Allow",
                "LockDomain",
                "TemplateBase");
            this.TemplateBase = this.TemplateBase ?? "~/DataFiles/Templates/Default";
            return this;
        }

        public Site GetSite()
        {
            return Site.GetBySiteGuid(this.SiteGuid);
        }

        public string DataFilesPath
        {
            get
            {
                string root = this.GetSite().GetFileStorage().Location;
                if (this.FileStorageId.HasValue)
                {
                    root = FileStorage.GetAllFileStorages()[this.FileStorageId.Value].Location;
                }
                string folder = this.WareFolder;
                if (string.IsNullOrWhiteSpace(folder))
                {
                    folder = this.WareName;
                }
                return Ruandao.Misc.UtilityFunction.CombinePath(root,this.GetSite().SiteName, folder);
            }
        }

        public string GetConnectionString()
        {
            string dbname = this.WareDbName;

            if (!this.DatabaseId.HasValue && string.IsNullOrWhiteSpace(dbname))
            {
                return GetSite().GetDbConnectionString();
            }

            // 只要DatabaseId和WareDbName不同时为空就表示：网件不共享网站的数据库。
            Database db = GetSite().GetDatabase();
            if( this.DatabaseId.HasValue )
            // 为空表示使用网站的数据库实例。
            {
                db = Database.GetAllDatabases()[this.DatabaseId.Value];
            }
            if (string.IsNullOrWhiteSpace(dbname))
            // 为空表示使用约定的数据库名。
            {
                dbname = GetSite().SiteName + "_" + WareName;
            }
            return string.Format(db.Connection, db.Instance, dbname);
        }

        public string GetAccountConnectionString()
        {
            var site = this.GetSite();
            if (site.ContainsAccount)
            {
                return site.GetDbConnectionString();
            }
            return ConfigurationManager.ConnectionStrings["HostServer"].ConnectionString;
        }

        /// <summary>
        /// 不带地址和端口号的路径的映射,当以/{SitewareAppPath}/DataFiels/和~/DataFiles/打头时
        /// 不使用系统提供的路径映射，而是使用网件存储位置的特殊映射。
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetPhysicalPath(string url)
        {
            int pos;
            if (url.StartsWith("~/DataFiles/", true, null))
            {
                pos = 12; // DataFiles/后面一个字符的位置。
                return UtilityFunction.CombinePath(DataFilesPath, url.Substring(pos));
            }
            string path = VirtualPathUtility.ToAbsolute("~/DataFiles/");
            if (url.StartsWith(path, true, null))
            {
                pos = path.Length; // DataFiles/后面一个字符的位置。
                return UtilityFunction.CombinePath(DataFilesPath, url.Substring(pos));
            }

            return HttpContext.Current.Request.MapPath(url);
        }


    }
}
